from tools.db import db
from models.models import User, Role, Permission, Order, OrderItem, Address, Tag
from datetime import datetime
from sqlalchemy import and_, or_

class UserService:
    """用户服务类 - 一对多关系操作示例"""
    
    @staticmethod
    def create_user(username, email, password_hash=None):
        """创建用户"""
        user = User(
            username=username,
            email=email,
            password_hash=password_hash
        )
        db.session.add(user)
        db.session.commit()
        return user
    
    @staticmethod
    def get_user_by_id(user_id):
        """根据ID获取用户"""
        return User.query.get(user_id)
    
    @staticmethod
    def get_user_by_username(username):
        """根据用户名获取用户"""
        return User.query.filter_by(username=username).first()
    
    @staticmethod
    def get_all_users():
        """获取所有用户"""
        return User.query.all()
    
    @staticmethod
    def update_user(user_id, **kwargs):
        """更新用户信息"""
        user = User.query.get(user_id)
        if user:
            for key, value in kwargs.items():
                if hasattr(user, key):
                    setattr(user, key, value)
            user.updated_at = datetime.utcnow()
            db.session.commit()
            return user
        return None
    
    @staticmethod
    def delete_user(user_id):
        """删除用户（会级联删除相关数据）"""
        user = User.query.get(user_id)
        if user:
            db.session.delete(user)
            db.session.commit()
            return True
        return False
    
    # 一对多关系操作
    @staticmethod
    def get_user_orders(user_id):
        """获取用户的所有订单"""
        user = User.query.get(user_id)
        return user.orders.all() if user else []
    
    @staticmethod
    def get_user_addresses(user_id):
        """获取用户的所有地址"""
        user = User.query.get(user_id)
        return user.addresses.all() if user else []
    
    @staticmethod
    def add_user_address(user_id, name, phone, province, city, district, street, postal_code=None, is_default=False):
        """为用户添加地址"""
        user = User.query.get(user_id)
        if user:
            # 如果设置为默认地址，先取消其他默认地址
            if is_default:
                Address.query.filter_by(user_id=user_id, is_default=True).update({'is_default': False})
            
            address = Address(
                name=name,
                phone=phone,
                province=province,
                city=city,
                district=district,
                street=street,
                postal_code=postal_code,
                is_default=is_default,
                user_id=user_id
            )
            db.session.add(address)
            db.session.commit()
            return address
        return None
    
    # 多对多关系操作
    @staticmethod
    def assign_role_to_user(user_id, role_id):
        """为用户分配角色"""
        user = User.query.get(user_id)
        role = Role.query.get(role_id)
        if user and role:
            if role not in user.roles:
                user.roles.append(role)
                db.session.commit()
                return True
        return False
    
    @staticmethod
    def remove_role_from_user(user_id, role_id):
        """移除用户角色"""
        user = User.query.get(user_id)
        role = Role.query.get(role_id)
        if user and role:
            if role in user.roles:
                user.roles.remove(role)
                db.session.commit()
                return True
        return False
    
    @staticmethod
    def get_user_roles(user_id):
        """获取用户的所有角色"""
        user = User.query.get(user_id)
        return user.roles.all() if user else []
    
    @staticmethod
    def assign_tag_to_user(user_id, tag_id):
        """为用户添加标签"""
        user = User.query.get(user_id)
        tag = Tag.query.get(tag_id)
        if user and tag:
            if tag not in user.tags:
                user.tags.append(tag)
                db.session.commit()
                return True
        return False
    
    @staticmethod
    def remove_tag_from_user(user_id, tag_id):
        """移除用户标签"""
        user = User.query.get(user_id)
        tag = Tag.query.get(tag_id)
        if user and tag:
            if tag in user.tags:
                user.tags.remove(tag)
                db.session.commit()
                return True
        return False
    
    @staticmethod
    def get_user_tags(user_id):
        """获取用户的所有标签"""
        user = User.query.get(user_id)
        return user.tags.all() if user else []

class OrderService:
    """订单服务类 - 一对多关系操作示例"""
    
    @staticmethod
    def create_order(user_id, order_number, total_amount, status='pending'):
        """创建订单"""
        order = Order(
            user_id=user_id,
            order_number=order_number,
            total_amount=total_amount,
            status=status
        )
        db.session.add(order)
        db.session.commit()
        return order
    
    @staticmethod
    def get_order_by_id(order_id):
        """根据ID获取订单"""
        return Order.query.get(order_id)
    
    @staticmethod
    def get_orders_by_user(user_id):
        """获取用户的所有订单"""
        return Order.query.filter_by(user_id=user_id).all()
    
    @staticmethod
    def update_order_status(order_id, status):
        """更新订单状态"""
        order = Order.query.get(order_id)
        if order:
            order.status = status
            order.updated_at = datetime.utcnow()
            db.session.commit()
            return order
        return None
    
    @staticmethod
    def delete_order(order_id):
        """删除订单（会级联删除订单项）"""
        order = Order.query.get(order_id)
        if order:
            db.session.delete(order)
            db.session.commit()
            return True
        return False
    
    # 一对多关系操作
    @staticmethod
    def add_order_item(order_id, product_name, quantity, unit_price):
        """为订单添加订单项"""
        order = Order.query.get(order_id)
        if order:
            total_price = quantity * unit_price
            order_item = OrderItem(
                order_id=order_id,
                product_name=product_name,
                quantity=quantity,
                unit_price=unit_price,
                total_price=total_price
            )
            db.session.add(order_item)
            
            # 更新订单总金额
            order.total_amount = sum(item.total_price for item in order.order_items)
            order.updated_at = datetime.utcnow()
            
            db.session.commit()
            return order_item
        return None
    
    @staticmethod
    def get_order_items(order_id):
        """获取订单的所有订单项"""
        order = Order.query.get(order_id)
        return order.order_items.all() if order else []
    
    @staticmethod
    def remove_order_item(order_item_id):
        """删除订单项"""
        order_item = OrderItem.query.get(order_item_id)
        if order_item:
            order = order_item.order
            db.session.delete(order_item)
            
            # 重新计算订单总金额
            order.total_amount = sum(item.total_price for item in order.order_items)
            order.updated_at = datetime.utcnow()
            
            db.session.commit()
            return True
        return False

class RoleService:
    """角色服务类 - 多对多关系操作示例"""
    
    @staticmethod
    def create_role(name, description=None):
        """创建角色"""
        role = Role(name=name, description=description)
        db.session.add(role)
        db.session.commit()
        return role
    
    @staticmethod
    def get_role_by_id(role_id):
        """根据ID获取角色"""
        return Role.query.get(role_id)
    
    @staticmethod
    def get_all_roles():
        """获取所有角色"""
        return Role.query.all()
    
    @staticmethod
    def update_role(role_id, name=None, description=None):
        """更新角色信息"""
        role = Role.query.get(role_id)
        if role:
            if name is not None:
                role.name = name
            if description is not None:
                role.description = description
            db.session.commit()
            return role
        return None
    
    @staticmethod
    def delete_role(role_id):
        """删除角色"""
        role = Role.query.get(role_id)
        if role:
            db.session.delete(role)
            db.session.commit()
            return True
        return False
    
    # 多对多关系操作
    @staticmethod
    def assign_permission_to_role(role_id, permission_id):
        """为角色分配权限"""
        role = Role.query.get(role_id)
        permission = Permission.query.get(permission_id)
        if role and permission:
            if permission not in role.permissions:
                role.permissions.append(permission)
                db.session.commit()
                return True
        return False
    
    @staticmethod
    def remove_permission_from_role(role_id, permission_id):
        """移除角色权限"""
        role = Role.query.get(role_id)
        permission = Permission.query.get(permission_id)
        if role and permission:
            if permission in role.permissions:
                role.permissions.remove(permission)
                db.session.commit()
                return True
        return False
    
    @staticmethod
    def get_role_permissions(role_id):
        """获取角色的所有权限"""
        role = Role.query.get(role_id)
        return role.permissions.all() if role else []
    
    @staticmethod
    def get_users_with_role(role_id):
        """获取拥有指定角色的所有用户"""
        role = Role.query.get(role_id)
        return role.users.all() if role else []

class PermissionService:
    """权限服务类"""
    
    @staticmethod
    def create_permission(name, resource, action):
        """创建权限"""
        permission = Permission(name=name, resource=resource, action=action)
        db.session.add(permission)
        db.session.commit()
        return permission
    
    @staticmethod
    def get_permission_by_id(permission_id):
        """根据ID获取权限"""
        return Permission.query.get(permission_id)
    
    @staticmethod
    def get_all_permissions():
        """获取所有权限"""
        return Permission.query.all()
    
    @staticmethod
    def get_permissions_by_resource(resource):
        """根据资源获取权限"""
        return Permission.query.filter_by(resource=resource).all()
    
    @staticmethod
    def update_permission(permission_id, name=None, resource=None, action=None):
        """更新权限信息"""
        permission = Permission.query.get(permission_id)
        if permission:
            if name is not None:
                permission.name = name
            if resource is not None:
                permission.resource = resource
            if action is not None:
                permission.action = action
            db.session.commit()
            return permission
        return None
    
    @staticmethod
    def delete_permission(permission_id):
        """删除权限"""
        permission = Permission.query.get(permission_id)
        if permission:
            db.session.delete(permission)
            db.session.commit()
            return True
        return False

class TagService:
    """标签服务类 - 多对多关系操作示例"""
    
    @staticmethod
    def create_tag(name, color='#409EFF', description=None):
        """创建标签"""
        tag = Tag(name=name, color=color, description=description)
        db.session.add(tag)
        db.session.commit()
        return tag
    
    @staticmethod
    def get_tag_by_id(tag_id):
        """根据ID获取标签"""
        return Tag.query.get(tag_id)
    
    @staticmethod
    def get_all_tags():
        """获取所有标签"""
        return Tag.query.all()
    
    @staticmethod
    def update_tag(tag_id, name=None, color=None, description=None):
        """更新标签信息"""
        tag = Tag.query.get(tag_id)
        if tag:
            if name is not None:
                tag.name = name
            if color is not None:
                tag.color = color
            if description is not None:
                tag.description = description
            db.session.commit()
            return tag
        return None
    
    @staticmethod
    def delete_tag(tag_id):
        """删除标签"""
        tag = Tag.query.get(tag_id)
        if tag:
            db.session.delete(tag)
            db.session.commit()
            return True
        return False
    
    @staticmethod
    def get_users_with_tag(tag_id):
        """获取拥有指定标签的所有用户"""
        tag = Tag.query.get(tag_id)
        return tag.users.all() if tag else []

class AddressService:
    """地址服务类 - 一对多关系操作示例"""
    
    @staticmethod
    def create_address(user_id, name, phone, province, city, district, street, postal_code=None, is_default=False):
        """创建地址"""
        # 如果设置为默认地址，先取消其他默认地址
        if is_default:
            Address.query.filter_by(user_id=user_id, is_default=True).update({'is_default': False})
        
        address = Address(
            user_id=user_id,
            name=name,
            phone=phone,
            province=province,
            city=city,
            district=district,
            street=street,
            postal_code=postal_code,
            is_default=is_default
        )
        db.session.add(address)
        db.session.commit()
        return address
    
    @staticmethod
    def get_address_by_id(address_id):
        """根据ID获取地址"""
        return Address.query.get(address_id)
    
    @staticmethod
    def get_addresses_by_user(user_id):
        """获取用户的所有地址"""
        return Address.query.filter_by(user_id=user_id).all()
    
    @staticmethod
    def get_default_address(user_id):
        """获取用户的默认地址"""
        return Address.query.filter_by(user_id=user_id, is_default=True).first()
    
    @staticmethod
    def set_default_address(address_id):
        """设置默认地址"""
        address = Address.query.get(address_id)
        if address:
            # 先取消该用户的其他默认地址
            Address.query.filter_by(user_id=address.user_id, is_default=True).update({'is_default': False})
            # 设置当前地址为默认
            address.is_default = True
            db.session.commit()
            return address
        return None
    
    @staticmethod
    def update_address(address_id, **kwargs):
        """更新地址信息"""
        address = Address.query.get(address_id)
        if address:
            for key, value in kwargs.items():
                if hasattr(address, key):
                    setattr(address, key, value)
            db.session.commit()
            return address
        return None
    
    @staticmethod
    def delete_address(address_id):
        """删除地址"""
        address = Address.query.get(address_id)
        if address:
            db.session.delete(address)
            db.session.commit()
            return True
        return False

